package org.kl.bf.web.basic;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.kl.bf.entity.basic.HelpDocument;
import org.kl.bf.entity.easyui.EasyuiTreeNode;
import org.kl.bf.service.ServiceException;
import org.kl.bf.service.basic.HelpDocumentService;
import org.kl.bf.web.base.BasicController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.utils.Collections3;
import org.springside.modules.web.MediaTypes;

@Controller
@RequestMapping(value = "basic/helpDocument")
public class HelpDocumentController extends BasicController{
	
	@Autowired
	private HelpDocumentService helpDocumentService;

	@RequestMapping(method = RequestMethod.GET)
	public String list() {
		return "basic/helpDocumentList";
	}

	/**
	 * 
	 * @param id
	 *            节点编码，不是主键的id
	 * @param model
	 * @param request
	 * @return
	 */
	//@SuppressWarnings("unchecked")
	@RequestMapping(value = "tree", method = RequestMethod.GET, produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String tree(@RequestParam(value = "id", defaultValue = "") String id, Model model, ServletRequest request) {
		List<HelpDocument> helpDocumentList = new ArrayList<HelpDocument>();
		helpDocumentList = helpDocumentService.getAllHelpDocument();
		/*if (StringUtils.isBlank(id)) {
			List<HelpDocument> root = helpDocumentService.findRoot();
			if (root != null) {
				helpDocumentList.addAll(root);
				//System.out.println("结果是"+root.get(0).getOrgName());
			}
			List<HelpDocument> rootChildren = helpDocumentService.findByHelpDocumentsHelpParentIdIn(Collections3.extractToList(root, "id"));
			
			
			if (rootChildren != null) {
				helpDocumentList.addAll(rootChildren);
			}
		} else {
			//helpDocumentList = helpDocumentService.findById(id);
		}*/
		List<EasyuiTreeNode> plainTree = new ArrayList<EasyuiTreeNode>();
		for (HelpDocument helpDocument : helpDocumentList) {
			EasyuiTreeNode one = helpDocumentToTreeNode(helpDocument);
			plainTree.add(one);
		}
		String result = jsonMapper.toJson(plainTree);
		return result;
	}

	private EasyuiTreeNode helpDocumentToTreeNode(HelpDocument helpDocument) {
		EasyuiTreeNode one = new EasyuiTreeNode();
		one.setId(helpDocument.getId());
		one.setText(helpDocument.getHelpDocTitle());
		one.setPid(helpDocument.getHelpParentId());
		Map<String, Object> attributes = new HashMap<String, Object>();
		attributes.put("id", helpDocument.getId());
		//attributes.put("orgNo", organization.getOrgNo());
		attributes.put("helpDocTitle", helpDocument.getHelpDocTitle());
		attributes.put("helpDocType", helpDocument.getHelpDocType());
		attributes.put("remark", helpDocument.getRemark());
		one.setAttributes(attributes);

		if (StringUtils.isNotBlank(helpDocument.getHelpParentId()) && organizationService.childrenCount(helpDocument.getHelpDocTitle()) > 0) {
			one.setState("closed");
		}
		return one;
	}
	
	@RequestMapping(value = "content", method = RequestMethod.POST, produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String content(@RequestParam(value = "id") String id,Model model, ServletRequest request) throws Exception {
		String result = null;
		if (StringUtils.isBlank(id)) {
			result = ajaxMsg("文档唯一标识获取失败，无法查看，请刷新重试",false,null);
		} else {
			HelpDocument helpDocument = helpDocumentService.getHelpDocument(id);
			
			if(helpDocument!=null){
				result = ajaxMsg("",true,helpDocument);
			}else{
				result = ajaxMsg("没有相关内容",false,null);
			}
			
		}
		return result;
	}

	@RequestMapping(value = "update", method = RequestMethod.POST, produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String update(@Valid @ModelAttribute("helpDocument") HelpDocument helpDocument, ServletRequest request, RedirectAttributes redirectAttributes) {
		try {
			System.out.println("父ID："+helpDocument.getHelpParentId());
			if(helpDocument.getHelpParentId().equals("")){
				if(StringUtils.isBlank(helpDocument.getId())){
					helpDocument.setHelpDocTitle("新根节点");
				}
				
			}else{
				HelpDocument hd = helpDocumentService.getHelpDocument(helpDocument.getHelpParentId());
				if(hd!=null){
					if (StringUtils.isBlank(helpDocument.getId())) {
						helpDocument.setHelpDocType(hd.getHelpDocType());
						helpDocument.setHelpDocTitle("新子节点");
					}else{						
							helpDocument.setHelpDocType(hd.getHelpDocType());
						
					}
				}
			}
			List<HelpDocument> helpDocumentList = helpDocumentService.findById(helpDocument.getId());
			if (Collections3.isNotEmpty(helpDocumentList)) {
				if (helpDocumentList.size() > 1 || !helpDocumentList.get(0).getId().equals(helpDocument.getId())) {
					return ajaxMsg("保存失败，PBS代码" + helpDocument.getHelpDocTitle() + "已经存在", false, null);
				}
			}
			if (StringUtils.isNotEmpty(helpDocument.getHelpParentId())) {
				helpDocumentList = helpDocumentService.findById(helpDocument.getHelpParentId());
				//System.out.println("测试"+organizationList.get(0).getOrgName());
				if (Collections3.isEmpty(helpDocumentList)) {
					return ajaxMsg("保存失败，" + helpDocument.getHelpDocTitle()  + "的父节点" + helpDocument.getHelpParentId()
							+ "不存在，请选中节点后再新增", false, null);
				}
			}
			//System.out.println("标题："+helpDocument.getHelpDocTitle()+"类型："+helpDocument.getHelpDocType().getCodeName());
			helpDocumentService.saveHelpDocument(helpDocument);
			return ajaxMsg("保存成功", true, helpDocumentToTreeNode(helpDocument));
		} catch (Exception e) {
			e.printStackTrace();
			return ajaxMsg("保存失败", false, null);
		}
	}

	@RequestMapping(value = "delete", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String delete(@RequestParam(value = "ids", defaultValue = "") String ids, RedirectAttributes redirectAttributes) {
		try {
			if (StringUtils.isBlank(ids)) {
				return ajaxMsg("请先勾选需要删除的节点", false, null);
			}
			int count = helpDocumentService.batchDeleteHelpDocument(ids);
			return ajaxMsg("成功删除" + count + "条", true, null);
		} catch (ServiceException se) {
			return ajaxMsg(se.getMessage(), false, null);
		} catch (Exception e) {
			e.printStackTrace();
			return ajaxMsg("删除失败", false, null);
		}
	}

	/*@RequestMapping(value = "excelExport", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String excelExport(@RequestParam(value = "pageNumber", defaultValue = "1") int pageNumber,
			@RequestParam(value = "sort", defaultValue = "pbsNodeCode") String sortType,
			@RequestParam(value = "order", defaultValue = "asc") String orderType, Model model, ServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> searchParams = KLServlets.getParametersStartingWith(request, SEARCH_PREFIX);
		Page<Pbs> pbsPage = pbsService.getPbs(searchParams, pageNumber, 0, sortType, orderType);
		try {
			// 输出Excel文件.
			response.setContentType("application/vnd.ms-excel");
			response.setHeader("Content-Disposition",
					"attachment;filename=\""
							+ new String(("PBS" + new DateTime().toString("yyyyMMddHHmmss") + ".xls").getBytes("gb2312"), "ISO8859-1")
							+ "\"");
			ExcelWriter.exportExcel("PBS", Pbs.class, pbsPage.getContent(), response.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				response.getOutputStream().flush();
				response.getOutputStream().close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}*/

	/**
	 * 所有RequestMapping方法调用前的Model准备方法, 实现Struts2
	 * Preparable二次部分绑定的效果,先根据form的id从数据库查出Task对象,再把Form提交的内容绑定到该对象上。
	 * 因为仅update()方法的form中有id属性，因此仅在update时实际执行.
	 */
	@ModelAttribute
	public void getMenu(@RequestParam(value = "id", defaultValue = "-1") String id, Model model) {
		if (!id.equals("-1")) {
			model.addAttribute("helpDocument", helpDocumentService.getHelpDocument(id));
		} else {
			model.addAttribute("helpDocument", new HelpDocument());
		}
	}

}
